﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace DynamicDNS.Wpf
{
    public class ServiceManagement : INotifyPropertyChanged
    {
        private static readonly ServiceManagement instance;
        private ServiceController Controller;

        public static ServiceManagement Instance { get { return instance; } }

        private ServiceManagement()
        {
            Controller = new ServiceController("DynamicDNS", System.Environment.MachineName);
        }
        static ServiceManagement()
        {
            instance = new ServiceManagement();
        }

        public void Start()
        {
            Controller.Start();
            WaitForStatus(ServiceControllerStatus.Running);
        }

        public void Stop()
        {
            Controller.Stop();
            WaitForStatus(ServiceControllerStatus.Stopped);
        }

        private void WaitForStatus(ServiceControllerStatus desired)
        {
            Controller.Refresh();
            Controller.WaitForStatus(desired);
            OnPropertyChanged("Status");
        }

        public string Status
        {
            get
            {
                return Controller.Status.ToString();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string property)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}
